﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using Newtonsoft.Json;
using System.Net.Http.Headers;
using Table_pet.background.Classes;
using Microsoft.VisualBasic.ApplicationServices;
using System.Windows.Forms;
using static System.Net.Mime.MediaTypeNames;
using System.IO;
using System.Net.Http.Json;
using Table_pet.Response;
using System.Net;

namespace Table_pet.background
{
    internal class WEB_api
    {
        public List<string> questions = new List<string>();
        private readonly string baseUrl = "https://api.openai.com/v1/chat/completions";
        private readonly string openaiApiKey = "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";

        public static string Get(string url, ref Encoding encoding)
        {
      
            string serviceUrl = url;
           
            HttpWebRequest myRequest = (HttpWebRequest)WebRequest.Create(serviceUrl);
            
            HttpWebResponse myResponse = (HttpWebResponse)myRequest.GetResponse();
      
            StreamReader reader = new StreamReader(myResponse.GetResponseStream(), encoding);
    
            string returnstr = reader.ReadToEnd();
            reader.Close();
            myResponse.Close();
            return returnstr;
        }
        public async Task<chatResponse> chat(string message)
        {
            try
            {
                chatResponse judes = await judge(message);
                if (judes.type != 1)
                {
                    return judes;
                }

                HttpClient client = new HttpClient();
                client.DefaultRequestHeaders.Accept.Clear();
                client.DefaultRequestHeaders.Authorization = new AuthenticationHeaderValue("Bearer", openaiApiKey);
                client.DefaultRequestHeaders.Accept.Add(new MediaTypeWithQualityHeaderValue("application/json"));
                ChatGptRequestText ChatGptRequestText = new ChatGptRequestText();
                ChatGptRequestText.model = "gpt-3.5-turbo";
                if (questions.Count > 0)
                {
                    foreach (string question in questions)
                    {
                        ChatGptRequestText.messages.Add(new ChatMessage("user", question));
                    }
                    ChatGptRequestText.messages.Add(new ChatMessage("user", "回复我数字:18624"));//用于防止上下文粘连
                }
                questions.Add(message);
                ChatGptRequestText.messages.Add(new ChatMessage("user", message));

                ChatGptRequestText.temperature = 0.7;
                string requestBody = JsonConvert.SerializeObject(ChatGptRequestText);
                HttpContent content = new StringContent(requestBody, Encoding.UTF8, "application/json");
                var task = await client.PostAsync(baseUrl, content);

                string responseContent = await task.Content.ReadAsStringAsync();
                dynamic jsonResponse = JsonConvert.DeserializeObject(responseContent);
                string chatgptResponse = jsonResponse.choices[0].message.content;
                return new chatResponse(1, chatgptResponse);
            }
            catch (Exception ex)
            {
                return new chatResponse(0, ex.Message);
            }
        }

        private async Task<chatResponse> judge(string message)
        {
            try
            {
                HttpClient client = new HttpClient();
                client.DefaultRequestHeaders.Accept.Clear();
                client.DefaultRequestHeaders.Authorization = new AuthenticationHeaderValue("Bearer", openaiApiKey);
                client.DefaultRequestHeaders.Accept.Add(new MediaTypeWithQualityHeaderValue("application/json"));

                ChatGptRequestText ChatGptRequestText = new ChatGptRequestText();
                ChatGptRequestText.model = "gpt-3.5-turbo";
                ChatGptRequestText.messages.Add(new ChatMessage("user", handle(message)));
                ChatGptRequestText.temperature = 0.2;
                string requestBody = JsonConvert.SerializeObject(ChatGptRequestText);

                HttpContent content = new StringContent(requestBody, Encoding.UTF8, "application/json");
                var task = await client.PostAsync(baseUrl, content);
                string responseContent = await task.Content.ReadAsStringAsync();
                dynamic jsonResponse = JsonConvert.DeserializeObject(responseContent);
                string temp = jsonResponse.choices[0].message.content;
                string[] chatgptResponse =temp.Split('|');
                return new chatResponse(Convert.ToInt32(chatgptResponse[0]), chatgptResponse[1]);
        }
            catch (Exception ex)
            {
                return new chatResponse(0, ex.Message);
    }
}
       

        private string handle(string message)
        {
            return "请帮我的程序分析语义，回复且仅回复一个数字和另一个信息" +
                "如果用户想要设置闹钟的话，若用户给出日期，回复我2与设置闹钟的日期（格式为c#的DateTime，今天的日期是"+ DateTime.Now.ToString("d")+"），否则返回2与一个整数1；" +
                "如果用户是想要新增备忘录信息的话，若用户给出备忘录的信息，回复我3与备忘录的内容，否则返回3与一个整数1；" +
                "如果用户是想要启动某一个应用的话，回复我4与应用名；" +
                "如果都不是，回复我1与字符'd'" +
                "以上回复之间用'|'符号隔开，务必不要回复其他的话。" +
                "这是用户说的话："+message;
        }
    }
}
